import re

from django.shortcuts import render
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.decorators import action
from rest_framework.exceptions import APIException, ValidationError
from rest_framework.mixins import CreateModelMixin, UpdateModelMixin, RetrieveModelMixin, ListModelMixin
from rest_framework.viewsets import GenericViewSet, ViewSet
from .serializers import LoginSerializer, SmsLoginSerializer, UserSerializer, ModifySerializer, PasswordSerializer, \
    VipSerializer, ComichistorySerizlizer
from app01.utils.response import APIResponse
from .models import User, Vip, Comchistory
from django.core.cache import cache
from app01.libs import tencent_sms_v3 as tencent_sms
from rest_framework.response import Response


class LoginViewSet(GenericViewSet):
    queryset = User.objects.all()
    serializer_class = LoginSerializer

    def get_serializer_class(self):

        if self.action == 'sms_login':
            return SmsLoginSerializer
        else:
            return self.serializer_class

    def common_login(self, request):
        ser = self.get_serializer(data=request.data, context={'request': request})
        ser.is_valid(raise_exception=True)
        token = ser.context.get('token')
        icon = ser.context.get('icon')
        username = ser.context.get('username')
        user_id = ser.context.get('id')
        return APIResponse(token=token, icon=icon, username=username, id=user_id)

    @action(methods=['post'], detail=False)
    def mul_login(self, request):
        return self.common_login(request)

    @action(methods=['POST'], detail=False)
    def sms_login(self, request):
        return self.common_login(request)


class MobileView(ViewSet):
    def list(self, request):
        try:
            phone = request.query_params.get('mobile')
            User.objects.get(mobile=phone)
            return APIResponse()
        except:
            return APIResponse(code=101, msg='手机号未注册', detail='手机号不存在')
            # raise APIException(detail='手机号不存在')


class SMSView(ViewSet):
    @action(methods=['GET'], detail=False)
    def send_sms(self, request):
        mobile = request.query_params.get('mobile')
        if mobile and re.match(r'^1[3-9][0-9]{9}$', mobile):
            code = tencent_sms.get_code()
            cache.set('sms_cache_%s' % mobile, code, 60)
            print(code)
            res = tencent_sms.send_sms(mobile, code)

            if res:
                return APIResponse(msg='信息发送成功')
            else:
                raise APIException(detail='发送短信失败')
        else:
            raise APIException(detail='手机号有误')


class UserView(GenericViewSet, CreateModelMixin):
    serializer_class = UserSerializer
    queryset = User.objects.all()

    def create(self, request, *args, **kwargs):
        super().create(request, *args, **kwargs)
        return APIResponse(msg='注册成功')


class ModifyView(GenericViewSet, UpdateModelMixin, RetrieveModelMixin):
    serializer_class = ModifySerializer
    queryset = User.objects.all()


class ModifyPassword(GenericViewSet, UpdateModelMixin):
    serializer_class = PasswordSerializer
    queryset = User.objects.all()

    def update(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, context={'request': request})
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        return APIResponse(msg='密码修改成功')


class GetVipView(GenericViewSet, ListModelMixin, CreateModelMixin, UpdateModelMixin):
    queryset = Vip.objects.all()
    serializer_class = VipSerializer
    filter_backends = [DjangoFilterBackend, ]
    filterset_fields = ['user']

    def list(self, request, *args, **kwargs):
        try:
            queryset = self.filter_queryset(self.get_queryset())
            page = self.paginate_queryset(queryset)
            if page is not None:
                serializer = self.get_serializer(page, many=True)
                return self.get_paginated_response(serializer.data)
            serializer = self.get_serializer(queryset, many=True)

            return Response(serializer.data)
        except APIException:
            return APIResponse(is_vip=False, code=101, msg='当前用户不是会员')


class CreateVipView(GenericViewSet, CreateModelMixin, UpdateModelMixin):
    queryset = Vip.objects.all()
    serializer_class = VipSerializer


class ComicHistoryView(GenericViewSet, ListModelMixin, CreateModelMixin):
    queryset = Comchistory.objects.all()
    serializer_class = ComichistorySerizlizer
